<script setup lang="ts">
import type {Account} from "~/pojo/Account";

const tableData: Ref<Account[]> = ref([])
const search = ref('')

async function getOnlineList() {
  await cFetch<Account[]>('/account/online', {
    auth: true,
    defaultOpts: {
      method: "GET",
    }
  }).then(res => {
    tableData.value = res.data
  })
}

const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !search.value ||
            data.username.toLowerCase().includes(search.value.toLowerCase()) ||
            data.phone.toLowerCase().includes(search.value.toLowerCase())
    )
)

const handleOffline =(index: number, row: Account) => {
  ElMessageBox.confirm(
      `确认强制下线用户 ${row.username} ？`,
      '警告',
      {
        confirmButtonText: '强制下线',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        confirmButtonClass: 'warning-confirm-btn'
      }
  ).then(() => {
    cFetch('/account/offline', {
      auth: true,
      defaultOpts: {
        method: "DELETE",
        query: {
          id: row.id
        }
      }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('下线成功')
        getOnlineList()
      }
    })
  }).catch(() => {
    ElMessage.success('取消操作')
  })


}
async function refreshData(){
  await getOnlineList()
  ElMessage.success('刷新数据成功')
}
onMounted(function () {
  getOnlineList()
})
</script>

<template>
  <div>
    <el-table :data="filterTableData" style="width: 100%" height="85vh">
      <el-table-column label="用户名" prop="username"/>
      <el-table-column label="电话号" prop="phone"/>
      <el-table-column label="创建日期" prop="createdTime"/>
      <el-table-column label="更新时间" prop="updatedTime"/>
      <el-table-column align="right">
        <template #header>
          <div class="top-content">
            <el-tooltip
                effect="dark"
                content="刷新数据"
                placement="bottom"
            >
              <el-icon size="large" @click="refreshData" style="margin-right: 1rem;margin-top: 3px">
                <ElIconRefreshRight/>
              </el-icon>
            </el-tooltip>
            <el-input v-model="search" size="small" placeholder="Type to search"/>
          </div>

        </template>
        <template #default="scope">
          <el-button
              size="small"
              type="warning"
              @click="handleOffline(scope.$index, scope.row)"
          >
            强制下线
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style lang="scss">
.warning-confirm-btn {
  @extend .warning-btn
}

.top-content {
  display: flex;
  flex-direction: row;
}
</style>